package com.wh.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 
 *  Class Name: BufferTest1.java
 *  Description: nio操作读写流，拷贝文件的操作（使用byteBuffer操作）
 *  博客地址：http://ifeve.com/java-nio-channel-to-channel/
 *  @author wanghao  DateTime 2017年1月17日 下午3:44:46 
 *  @company hongbo
 *  @email 1228675455@qq.com
 */
public class BufferTest1 {
	
	public static void main(String[] args) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		ByteBuffer buf =  ByteBuffer.allocate(1024);
	    FileChannel inchannel = null;
	    FileChannel outchannel = null;
		try {
			fis = new FileInputStream("C://Users//wh//Desktop//openid上传文件说明(1).txt");
			fos = new FileOutputStream("D://nio//copy.txt");
			inchannel = fis.getChannel();
			outchannel = fos.getChannel();
			for(int i = 1; (i = inchannel.read(buf)) != -1;) {
				buf.flip();
				while(buf.hasRemaining()) {
					outchannel.write(buf);
				}
				buf.clear();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				outchannel.close();
				fos.close();
				inchannel.close();
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	} 

}
